package cn.ssm.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.HttpRequest;

import cn.ssm.alipay.AlipayConfig;
import cn.ssm.pojo.OrderDetail;
import cn.ssm.service.OrderCodeService;
import cn.ssm.service.OrderDetailService;
import cn.ssm.util.SmsDemo;

/**
 * 支付宝返回值控制层
 * 
 * @author 黄少涛
 *
 */
@Controller
@RequestMapping("/alipay")
public class palipayController {
	@Autowired
	private OrderDetailService orderDetailService;
	@Autowired
	private OrderCodeService orderCodeService;

	// 通过订单Id修改订单状态编号
	@RequestMapping("/updateOrder")
	public void updateOrder(HttpServletRequest request, HttpServletResponse response, HttpSession session) {

		try {
			Map<String, String> params = new HashMap<String, String>();
			Map<String, String[]> requestParams = request.getParameterMap();
			for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
				String name = (String) iter.next();
				String[] values = (String[]) requestParams.get(name);
				String valueStr = "";
				for (int i = 0; i < values.length; i++) {
					valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
				}
				// 乱码解决，这段代码在出现乱码时使用
				valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
				params.put(name, valueStr);
			}

			boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key,
					AlipayConfig.charset, AlipayConfig.sign_type); // 调用SDK验证签名

			if (signVerified) {

				// 商户订单号
				String out_trade_no = null;
				// 支付宝交易号
				String trade_no = null;
				// 付款金额
				String total_amount = null;

				out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

				trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

				total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

				if (out_trade_no != null && total_amount != null) {
					Map<String, Object> params2 = new HashMap<String, Object>();
					params2.put("orderId", out_trade_no); // 订单编号

					OrderDetail order = orderDetailService.getBuyTimeAndPhoneByOrderId(params2);
					double price =  Double.parseDouble(total_amount); // string转double
					if (order.getAdjustedPrice() == price) {
						params2.put("activeId", 2); // 状态编号
						int num = orderDetailService.updateOrder(params2); // 更新订单状态为已付款
						Date buyDate = order.getBuyDate(); // 获取购买时间
						long code = buyDate.getTime(); // 时间转换成数字
						String codeString = String.valueOf(code);
						String userPhone = (String) session.getAttribute("userPhone");
						if (userPhone != null) {
							SmsDemo.sendSms1(userPhone, codeString);
						} else {
							SmsDemo.sendSms1(order.getUserName(), codeString);
						}
						orderCodeService.addOrderCode(out_trade_no, codeString);
						
							
					}

					response.sendRedirect("/moviesMaven/html/myAccount.html");

				}

			}
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
